package com.chat.common.interceptor;

import com.chat.common.jwt.JwtUtil;
import com.chat.common.threadLocal.LoginUser;
import com.chat.common.threadLocal.UserContext;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null) {
            response.setStatus(401);
            return false;
        }
            Claims claims= JwtUtil.parseToken(token);
            String userId = claims.get("userId", String.class);
            String username = claims.get("username", String.class);
            UserContext.setUser(new LoginUser(userId, username));
            return true;

    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.clear();
    }
}
